package com.train.batch.listener;

import com.train.batch.enums.impl.JobOperationEnums;
import com.train.batch.event.JobSyncEvent;
import com.train.batch.service.QrtzJobRecordService;
import com.train.common.utils.exception.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JobSyncListener {

    @Autowired
    private QrtzJobRecordService qrtzJobRecordService;

    @EventListener
    public void handleJobSyncEvent(JobSyncEvent event) {
        log.info("开始执行定时任务同步, 任务名称:{}, 组名称:{}", event.getJobName(), event.getGroupName());
        String jobName = event.getJobName();
        String groupName = event.getGroupName();
        JobOperationEnums operationEnums = event.getOperationEnums();
        try {
            if (JobOperationEnums.ERROR_JOB.getCode().equals(operationEnums.getCode())) {
                qrtzJobRecordService.editJobStatus(jobName, groupName);
            } else if (JobOperationEnums.COMPLETE_JOB.getCode().equals(operationEnums.getCode())) {
                qrtzJobRecordService.editExecuteTime(jobName, groupName);
            }
        } catch (SchedulerException e) {
            log.error("同步任务记录失败, 失败原因:{}", ExceptionUtils.getExpMsg(e));
        }
    }
}
